$(document).ready(function() {
    let investmentDiarys = [];
    let portfolios = [];
    let totalPages = 1;
    let currentPage = 1;
    let itemsPerPage = 10;

    // 自定义alert函数
    function customAlert(message) {
        $('#customAlertMessage').text(message);
        $('#customAlertModal').modal('show');
    }

    // 获取所有投资组合用于下拉列表
    function fetchPortfolios() {
        $.ajax({
            url: `/api/portfolios/getAllPortfolios`,
            type: 'GET',
            success: function(data) {
                portfolios = data;
                renderPortfolioSelects();
            },
            error: function(xhr, status, error) {
                console.error('Error fetching portfolios:', error);
            }
        });
    }

    function renderPortfolioSelects() {
        const searchSelect = $('#searchPortfolioId');
        const addSelect = $('#addPortfolioId');
        const editSelect = $('#editPortfolioId');
        
        searchSelect.empty();
        addSelect.empty();
        editSelect.empty();
        
        searchSelect.append('<option value="">全部组合</option>');
        addSelect.append('<option value="">请选择</option>');
        editSelect.append('<option value="">请选择</option>');
        
        portfolios.forEach(portfolio => {
            searchSelect.append(`<option value="${portfolio.id}">${portfolio.portfolioName}</option>`);
            addSelect.append(`<option value="${portfolio.id}">${portfolio.portfolioName}</option>`);
            editSelect.append(`<option value="${portfolio.id}">${portfolio.portfolioName}</option>`);
        });
    }

    function fetchInvestmentDiarys() {
        const fundCode = $('#searchFundCode').val();
        const portfolioId = $('#searchPortfolioId').val();
        const category = $('#searchCategory').val();
        itemsPerPage = parseInt($('#itemsPerPage').val(), 10);
        const queryParams = {
            fundCode: fundCode || '',
            portfolioId: portfolioId || '',
            category: category || '',
            pageNo: currentPage,
            pageSize: itemsPerPage
        };

        $.ajax({
            url: `/api/investmentDiarys/getInvestmentDiarysByConditions`,
            type: 'GET',
            data: queryParams,
            success: function(data) {
                if (!data || !data.records) {
                    console.error('Invalid data received:', data);
                    customAlert('获取数据失败，请检查输入条件或稍后重试。');
                    return;
                }

                investmentDiarys = data.records;
                totalPages = data.pages;
                renderInvestmentDiaryTable(investmentDiarys);
                updatePagination();
            },
            error: function(xhr, status, error) {
                console.error('Error fetching investment diarys:', error);
                customAlert('获取数据失败，请检查网络连接或稍后重试。');
            }
        });
    }

    function renderInvestmentDiaryTable(data) {
        const investmentDiaryTableBody = $('#investmentDiaryTableBody');
        investmentDiaryTableBody.empty();

        if (data.length > 0) {
            data.forEach(diary => {
                const tr = $('<tr>');
                tr.append($('<td>').text(diary.title));
                tr.append($('<td>').text(diary.fundCode || ''));
                tr.append($('<td>').text(diary.portfolioName || ''));
                tr.append($('<td>').text(diary.categoryName));
                tr.append($('<td>').text(diary.createdTime || ''));
                
                const actionsTd = $('<td>');
                actionsTd.html(`
                    <button class="btn btn-sm btn-info me-2" onclick="showInvestmentDiary(${diary.id})">查看</button>
                    <button class="btn btn-sm btn-warning me-2" onclick="editInvestmentDiary(${diary.id})">编辑</button>
                    <button class="btn btn-sm btn-danger" onclick="deleteInvestmentDiary(${diary.id})">删除</button>
                `);
                tr.append(actionsTd);
                investmentDiaryTableBody.append(tr);
            });
        } else {
            investmentDiaryTableBody.html('<tr><td colspan="6" class="text-center">暂无数据</td></tr>');
        }
    }

    // 更新分页控件
    function updatePagination() {
        // 更新页码显示
        $('#currentPage').text(currentPage);
        $('#totalPages').text(totalPages);
        
        // 更新上一页和下一页按钮状态
        if (currentPage <= 1) {
            $('#prevPage').addClass('disabled');
        } else {
            $('#prevPage').removeClass('disabled');
        }
        
        if (currentPage >= totalPages) {
            $('#nextPage').addClass('disabled');
        } else {
            $('#nextPage').removeClass('disabled');
        }
    }

    function handleSizeChange(newSize) {
        itemsPerPage = newSize;
        currentPage = 1; // 重置到第一页
        fetchInvestmentDiarys();
    }

    function handleCurrentChange(newPage) {
        // 确保页码在有效范围内
        if (newPage < 1) newPage = 1;
        if (newPage > totalPages) newPage = totalPages;
        
        if (newPage !== currentPage) {
            currentPage = newPage;
            fetchInvestmentDiarys();
        }
    }

    function addNewInvestmentDiary() {
        const title = $('#addTitle').val();
        const fundCode = $('#addFundCode').val();
        const portfolioId = $('#addPortfolioId').val();
        const category = $('#addCategory').val();
        const content = $('#addContent').val();

        if (title.trim() === '') {
            customAlert('标题不能为空');
            return;
        }

        if (category === '') {
            customAlert('分类不能为空');
            return;
        }

        if (content.trim() === '') {
            customAlert('内容不能为空');
            return;
        }

        const newInvestmentDiary = {
            title: title,
            fundCode: fundCode || null,
            portfolioId: portfolioId || null,
            category: category,
            content: content
        };

        $.ajax({
            url: `/api/investmentDiarys/addInvestmentDiary`,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(newInvestmentDiary),
            success: function(data) {
                $('#addInvestmentDiaryForm')[0].reset();
                $('#addInvestmentDiaryModal').modal('hide');
                fetchInvestmentDiarys();
                customAlert('新增成功');
            },
            error: function(xhr, status, error) {
                console.error('Error adding investment diary:', error);
                customAlert('新增投资日记失败');
            }
        });
    }

    function saveEditInvestmentDiary() {
        const investmentDiaryId = $('#editInvestmentDiaryId').val();
        const title = $('#editTitle').val();
        const fundCode = $('#editFundCode').val();
        const portfolioId = $('#editPortfolioId').val();
        const category = $('#editCategory').val();
        const content = $('#editContent').val();

        if (title.trim() === '') {
            customAlert('标题不能为空');
            return;
        }

        if (category === '') {
            customAlert('分类不能为空');
            return;
        }

        if (content.trim() === '') {
            customAlert('内容不能为空');
            return;
        }

        const updatedInvestmentDiary = {
            id: investmentDiaryId,
            title: title,
            fundCode: fundCode || null,
            portfolioId: portfolioId || null,
            category: category,
            content: content
        };

        $.ajax({
            url: `/api/investmentDiarys/updateInvestmentDiary`,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(updatedInvestmentDiary),
            success: function(data) {
                $('#editInvestmentDiaryModal').modal('hide');
                fetchInvestmentDiarys();
                customAlert('信息更新成功');
            },
            error: function(xhr, status, error) {
                console.error('Error updating investment diary:', error);
                customAlert('更新投资日记失败');
            }
        });
    }

    function deleteInvestmentDiary(id) {
        if (confirm('确定要删除该投资日记吗？')) {
            $.ajax({
                url: `/api/investmentDiarys/deleteInvestmentDiary/${id}`,
                type: 'POST',
                success: function() {
                    fetchInvestmentDiarys();
                    customAlert('删除成功');
                },
                error: function(xhr, status, error) {
                    console.error('Error deleting investment diary:', error);
                    customAlert('删除投资日记失败');
                }
            });
        }
    }

    function showInvestmentDiary(id) {
        const diary = investmentDiarys.find(p => p.id == id);
        if (diary) {
            $('#detailInvestmentDiaryModalLabel').text(diary.title);
            $('#detailTitle').text(diary.title);
            $('#detailFundCode').text(diary.fundCode || '');
            $('#detailPortfolioName').text(diary.portfolioName || '');
            $('#detailCategory').text(diary.categoryName);
            $('#detailCreatedTime').text(diary.createdTime || '');
            $('#detailUpdatedTime').text(diary.updatedTime || '');
            $('#detailContent').text(diary.content || '');
            $('#detailInvestmentDiaryModal').modal('show');
        }
    }

    // 全局函数供HTML调用
    window.editInvestmentDiary = function(id) {
        const diary = investmentDiarys.find(p => p.id == id);
        if (diary) {
            $('#editInvestmentDiaryId').val(diary.id);
            $('#editTitle').val(diary.title);
            $('#editFundCode').val(diary.fundCode || '');
            $('#editPortfolioId').val(diary.portfolioId || '');
            $('#editCategory').val(diary.category);
            $('#editContent').val(diary.content || '');
            $('#editInvestmentDiaryModal').modal('show');
        }
    };

    window.showInvestmentDiary = showInvestmentDiary;
    window.deleteInvestmentDiary = deleteInvestmentDiary;

    // 事件绑定
    $('#fetchInvestmentDiarysButton').on('click', fetchInvestmentDiarys);
    $('#saveAddInvestmentDiary').on('click', addNewInvestmentDiary);
    $('#saveEditInvestmentDiary').on('click', saveEditInvestmentDiary);

    $('#itemsPerPage').on('change', function() {
        handleSizeChange(parseInt($(this).val(), 10));
    });

    $('#pPage').on('click', function(e) { 
        e.preventDefault();
        if (currentPage > 1) {
            handleCurrentChange(currentPage - 1); 
        }
    });
    
    $('#nPage').on('click', function(e) { 
        e.preventDefault();
        if (currentPage < totalPages) {
            handleCurrentChange(currentPage + 1); 
        }
    });

    // 初始化
    fetchPortfolios();
    fetchInvestmentDiarys();
});